<!--
 * @Author: 李金深 2896583081@qq.com
 * @Date: 2023-05-29 16:31:42
 * @LastEditors: 李金深 2896583081@qq.com
 * @LastEditTime: 2023-07-06 15:47:21
 * @FilePath: /com.huizhouyiren.web.d0101/src/components/publish/publish.vue
 * @Description: 动态发布组件
-->
<script setup>
import { ref, watch } from 'vue'
import mitt from '@/mitt/index'
import use$i18n from '@/hooks/use$i18n.js'
import { publishDynamicRequest } from '@/api/dynamic'
import { dataCheck } from '@/utils/check'
import Upload from '@/components/upload/upload.vue'

const $t = use$i18n()

let options = ref([
  {
    label: 'image',
    value: 'image'
  },
  {
    label: 'video',
    value: 'video'
  }
])
let fileType = ref('')

const initData = function () {
  options.value.forEach((item) => {
    item.label = $t(`email.${item.value}`)
  })
}
initData()
fileType.value = 'image'

let publishData = ref({
  pics: [],
  content: '',
  type: 0
})
let loading = ref(false)
/**
 * @description: 发布动态
 * @return {*}
 */
const publishDynamic = () => {
  let options = [
    {
      mode: 'require',
      key: 'content',
      message: $t('msg.inputText')
    }
  ]
  let result = dataCheck(publishData.value, options)
  if (result) {
    let data = {
      ...publishData.value
    }
    console.log(data.pics.length)
    data.pics.length > 0 ? (data.type = fileType.value == 'image' ? 1 : 2) : (data.type = 0)

    loading.value = true

    publishDynamicRequest(data)
      .then((res) => {
        if (res.code == 200) {
          mitt.emit('messageTip', {
            type: 'success',
            msg: res.msg
          })
          mitt.emit('dynamicPublish')
          resetpublishData()
        } else {
          mitt.emit('messageTip', {
            type: 'error',
            msg: res.msg
          })
        }
      })
      .finally(() => {
        loading.value = false
      })
  }
}
/**
 * @description: 数据重置
 * @return {*}
 */
const resetpublishData = () => {
  publishData.value = {
    pics: [],
    content: '',
    type: 0
  }
}

watch(
  () => fileType.value,
  () => {
    publishData.value.pics = []
  }
)

mitt.on('changeLanguage', () => {
  initData()
})
</script>
<template>
  <div>
    <div class="flex items-start">
      <n-input type="textarea" style="flex: 1" v-model:value="publishData.content" />
      <div class="ml-4">
        <div class="mb-3">
          <n-button type="primary" style="width: 6.25rem" @click="publishDynamic" :loading="loading">
            {{ $t('system.release') }}
          </n-button>
        </div>
      </div>
    </div>
    <div class="flex items-center mt-4">
      <div class="mr-2 text-sm text-gray-500">{{ $t('posts.type') }}</div>
      <n-select v-model:value="fileType" :options="options" style="width: 6.25rem" />
    </div>
    <div class="flex flex-wrap items-center mt-4">
      <Upload type="list" v-model:list="publishData.pics" :fileType="fileType" :max="fileType == 'picture' ? 9 : 1">
      </Upload>
    </div>
  </div>
</template>
<style></style>
